﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ePlanet.ArchiveBorrow.Models;
using ePlanet.ArchiveMange.Enum;
using System.Data;
using CommonModule;
using ePlanet.SingleWell.Services;
using DreamBuilder.Core.Container;
using ePlanet.SingleWell.Models;
using Web.SystemConfig.WorkFlow;
using ePlanet.ArchiveMange.Services;

namespace Web.Views.ArchiveBorrow.ArchiveBorrowView
{
    public partial class ArchiveBorrowView : System.Web.UI.MasterPage
    {
        #region 私有属性
        private bool m_CanView = false;
        private bool m_CanDownload = false;
        private string m_DBHelperString = string.Empty;
        private ArchiveBorrowModel.ARCHIVEBORROWRow m_CurrentArchiveBorrow = null;
        /// <summary>
        /// 当前档案借阅对象
        /// </summary>
        public ArchiveBorrowModel.ARCHIVEBORROWRow CurrentArchiveBorrow
        {
            get { return m_CurrentArchiveBorrow; }
            set { m_CurrentArchiveBorrow = value; }
        }

        private DataSet m_AttachData = null;
        /// <summary>
        /// 当前文档附件内容
        /// </summary>
        public DataSet AttachData
        {
            get { return m_AttachData; }
            set { m_AttachData = value; }
        }
        #endregion

        #region 页面事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (this.m_CurrentArchiveBorrow != null)
                {
                    m_CanView = this.m_CurrentArchiveBorrow.CANVIEW == 1 ? true : false;
                    m_CanDownload = this.m_CurrentArchiveBorrow.CANDOWNLOAD == 1 ? true : false;

                    if (this.m_CurrentArchiveBorrow.VALIDPERIOD > DateTime.Now)
                    {
                        DataTable jDataTable = null;
                        DataTable jnjDataTable = null;
                        bool isBindJNJ = false;
                        if (this.GetAttachData(out isBindJNJ, out jDataTable, out jnjDataTable))
                        {
                            if (isBindJNJ)
                            {
                                this.gv_jnjAttach.DataSource = jnjDataTable;
                                this.gv_jnjAttach.DataBind();
                            }
                            this.gv_jAttach.DataSource = jDataTable;
                            this.gv_jAttach.DataBind();

                            this.divJNJ.Visible = isBindJNJ;
                        }
                    }
                    else
                    {
                        Alert("此数据已经过期，将不能浏览附件数据！");
                    }
                }
                else
                {
                    Alert("获取借阅对象为空！");
                }
            }
        }

        protected void gv_Attach_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
            {
                if (!m_CanView)
                {
                    //设置浏览权限
                    e.Row.Cells[3].Visible = false;
                }
                if (!m_CanDownload)
                {
                    //设置下载权限
                    e.Row.Cells[2].Visible = false;
                }
            }
        }

        protected void gv_Attach_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "down")
            {
                DreamBuilder.UI.UserControls.EPGridView oEPGridView = sender as DreamBuilder.UI.UserControls.EPGridView;
                string attachmentID = ((DataTable)oEPGridView.DataSource).Rows[int.Parse(e.CommandArgument.ToString())][0].ToString();

                string dbHelperString = ((DataTable)oEPGridView.DataSource).Rows[int.Parse(e.CommandArgument.ToString())][4].ToString();

                if (!string.IsNullOrEmpty(dbHelperString) && !string.IsNullOrEmpty(attachmentID))
                {
                    this.DownloadAttachment(dbHelperString, attachmentID);
                }
                else
                {
                    Alert("下载数据失败，请刷新页面后重新操作。");
                }
            }
        }

        private void DownloadAttachment(string dbHelper, string attachmentID)
        {
            IAttachmentService oIAttachmentService = UContainer.Resolve<IAttachmentService>();
            oIAttachmentService.Initialize(dbHelper);
            AttachmentModel oAttachmentModel = oIAttachmentService.GetAttachmentModelByAttachmentID(attachmentID);
            byte[] data = oAttachmentModel.AttachmentContent;

            //Response.Clear();
            Response.AddHeader("Content-Disposition", "Application/pdf");
            Response.AddHeader("Content-Disposition", "attachment;filename=" + oAttachmentModel.AttachmentName);
            Response.BinaryWrite(data);
            Response.Flush();
            Response.End();
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 获取附件信息
        /// </summary>
        /// <returns></returns>
        private bool GetAttachData(out bool isBindJNJ, out DataTable jAttachment, out DataTable jnjAttachment)
        {
            isBindJNJ = false;
            jAttachment = null;
            jnjAttachment = null;

            switch ((ArchiveTableEnum)this.m_CurrentArchiveBorrow.ARCHIVETYPEID)
            {
                case ArchiveTableEnum.Account:
                case ArchiveTableEnum.AccountI01:
                case ArchiveTableEnum.AccountI02:
                case ArchiveTableEnum.AccountI03:
                case ArchiveTableEnum.AccountI04:
                    this.m_DBHelperString = AttachDbHelperString.AccountFile;
                    isBindJNJ = true;
                    break;
                case ArchiveTableEnum.AudioVedio:
                case ArchiveTableEnum.AudioVedioS01:
                case ArchiveTableEnum.AudioVedioS02:
                case ArchiveTableEnum.AudioVedioS03:
                    this.m_DBHelperString = AttachDbHelperString.Audiofile;
                    break;
                case ArchiveTableEnum.BulidProject:
                    this.m_DBHelperString = AttachDbHelperString.BuildProjectFile;
                    isBindJNJ = true;
                    break;
                case ArchiveTableEnum.CDKind:
                    this.m_DBHelperString = AttachDbHelperString.CDKind;
                    break;
                case ArchiveTableEnum.Document:
                    this.m_DBHelperString = AttachDbHelperString.DocumentFile;
                    break;
                case ArchiveTableEnum.Equipment:
                    this.m_DBHelperString = AttachDbHelperString.Equipment;
                    isBindJNJ = true;
                    break;
                case ArchiveTableEnum.OliSearch:
                case ArchiveTableEnum.OliSearchK01:
                case ArchiveTableEnum.OliSearchK02:
                    this.m_DBHelperString = AttachDbHelperString.Oilsearch;
                    break;
                case ArchiveTableEnum.RealKind:
                case ArchiveTableEnum.RealKindR01:
                case ArchiveTableEnum.RealKindR02:
                case ArchiveTableEnum.RealKindR03:
                case ArchiveTableEnum.RealKindR04:
                    this.m_DBHelperString = AttachDbHelperString.RealKind;
                    break;
                case ArchiveTableEnum.Technology:
                    this.m_DBHelperString = AttachDbHelperString.Technology;
                    isBindJNJ = true;
                    break;
                default:
                    throw new Exception("未知的文档类型");
            }
            //处理卷附件
            IAttachmentService oIAttachmentService = UContainer.Resolve<IAttachmentService>();
            oIAttachmentService.Initialize(this.m_DBHelperString);
            List<AttachmentModel> attachments = oIAttachmentService.GetAttachmentModelByObjectID(this.m_CurrentArchiveBorrow.ARCHIVEDATAID);
            TransAttachmentModelListToDataTable(out jAttachment, attachments, this.m_DBHelperString);

            //处理卷内件附件
            if (isBindJNJ)
            {
                IPageFileService oIPageFileService = UContainer.Resolve<IPageFileService>();
                DataTable pageFileDataTable = oIPageFileService.GetPageFileByArchiveIdListAndType(new List<string> { this.m_CurrentArchiveBorrow.ARCHIVEDATAID }, (int)this.m_CurrentArchiveBorrow.ARCHIVETYPEID);

                if (pageFileDataTable != null && pageFileDataTable.Rows.Count > 0)
                {
                    List<string> jnjIDs = new List<string>();
                    foreach (DataRow dr in pageFileDataTable.Rows)
                    {
                        jnjIDs.Add(dr["DataID"].ToString());
                    }

                    IAttachmentService jnjIAttachmentService = UContainer.Resolve<IAttachmentService>();
                    jnjIAttachmentService.Initialize(AttachDbHelperString.PageFile);
                    List<AttachmentModel> jnjAttachments = jnjIAttachmentService.GetAttachmentModelByObjectID(jnjIDs);
                    TransAttachmentModelListToDataTable(out jnjAttachment, jnjAttachments, AttachDbHelperString.PageFile);
                }
            }

            return true;
        }

        /// <summary>
        /// 转换附件数据类型
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="attachments"></param>
        private void TransAttachmentModelListToDataTable(out DataTable dataTable, List<AttachmentModel> attachments, string DBHelperString)
        {
            dataTable = new DataTable();
            if (attachments != null && attachments.Count > 0)
            {
                dataTable.Columns.Add("attachmentid");
                dataTable.Columns.Add("AttachmentName");
                dataTable.Columns.Add("UpdateTime");
                dataTable.Columns.Add("AttachmentSize");
                dataTable.Columns.Add("DBHelperString");
                dataTable.Columns.Add("uploadtime");

                foreach (AttachmentModel model in attachments)
                {
                    DataRow newRow = dataTable.NewRow();
                    newRow["attachmentid"] = model.AttachmentID;
                    newRow["AttachmentName"] = model.AttachmentName;
                    newRow["UpdateTime"] = model.UpdateTime.ToShortDateString();
                    newRow["AttachmentSize"] = (model.AttachmentSize / ((float)(1024 * 1024))).ToString() + "M";
                    newRow["uploadtime"] = model.UpdateTime.ToShortDateString();
                    newRow["DBHelperString"] = DBHelperString;

                    dataTable.Rows.Add(newRow);
                }
            }
        }

        /// <summary>
        /// 弹出框
        /// </summary>
        /// <param name="message"></param>
        private void Alert(string message)
        {
            Response.Write("<script>alert('" + message + "');</script>");
        }
        #endregion
    }
}